<style lang="scss" scoped="">
    @import "../utils/base.scss";
    .demo-drawer-footer{
        width: 100%;
        // position: absolute;
        bottom: 0;
        left: 0;
        border-top: 1px solid #e8e8e8;
        padding: 10px 16px;
        text-align: right;
        background: #fff;
    }
    .myText{
        max-width: 200px;
        max-height: 150px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
     }
    .ivu-table-stripe .ivu-table-body tr:nth-child(2n) td, .ivu-table-stripe .ivu-table-fixed-body tr:nth-child(2n) td {
        background-color: #ffffff;
    }
    td.ivu-table-expanded-cell {
      padding: 0px;
    }
</style>
<template>
    <div >
        <pheader>
            <template slot="left">用户管理/角色配置</template>
            <div style="text-align: right;margin-right: 18px;" slot="right">
                <Button type="primary" size="small" @click="add()" v-if="this.$hasPerm('roleAdd')">新增</Button>
                <Input v-model= "search_param" search placeholder="请输入角色名称"  style="width: auto;" @on-search="search($event,filterList,0)"/>
            </div>
        </pheader>
        <div style="padding: 8px 8px 0px 8px;">
            <div style="width: 100%;background-color: white;height: calc(100vh - 108px);overflow-y: auto;padding:10px;">
                <Table border :columns="columns" :data="data" :loading="tableLoading">
                    <template slot-scope="{ row, index }" slot="role_name">
                        <span>{{ row.role_name}}</span>
                    </template>
                    <template slot-scope="{ row, index }" slot="role_type">
                        <span v-if="row.role_type=='admin'">系统管理</span>
                        <span v-if="row.role_type=='business'">运营管理</span>
                        <span v-if="row.role_type=='operation'">运维管理</span>
                        <span v-if="row.role_type=='safe'">安全管理</span>
                        <span v-if="row.role_type=='entry'">普通角色</span>
                    </template>
                    <template slot-scope="{ row, index }" slot="des">
                        <div class="myText">
                            <span >{{row.des}}</span>
                        </div>
                    </template>
                    <template slot-scope="{ row, index }" slot="users">
                        <div class="myText">
                            <span >{{showUsers(row.users)}}</span>
                        </div>
                    </template>
                    <template slot-scope="{ row, index }" slot="action">
                        <div style="display: inline-block;">
                            <a v-if="$hasPerm('rolePerm')" href="javascript:void(0)" @click="permMenu(row.id,row.role_type)">
                                <div class="text_link" style="width: 80px;">
                                    权限管理
                                </div>
                            </a>
                            <a v-if="$hasPerm('roleEdit')" href="javascript:void(0)" @click="edit(index,row)">
                                <div class="text_link" style="width: 50px;">
                                    编辑
                                </div>
                            </a>
                            <a v-if="$hasPerm('roleMove')" href="javascript:void(0)" @click="deleteRole(row)">
                                <div class="text_link" style="width: 50px;">
                                    删除
                                </div>
                            </a>
                        </div>
                    </template>
                </Table>
                <div style="margin: 10px;overflow: hidden">
                    <div style="float: right;">
                        <Page :current="page" :total="total" show-total show-elevator show-sizer @on-change="changePage" @on-page-size-change="changePageSize"></Page>
                    </div>
                </div>
                <Modal @on-ok="add_ok()" @on-cancel="cancel('add_menu')"
                    v-model="add_menu.show" :mask-closable="false" :loading="loading"
                    :title="!add_menu.isupdate?'新增角色':'编辑角色'" width="720">
                    <Form ref="add_menu" :model="add_menu" :rules="ruleInline" label-position="left" :label-width="115">
                        <Row >
                            <Col span="23"style="width:97%" >
                                <FormItem label="角色名称：" prop="role_name">
                                    <Input v-model="add_menu.role_name" @on-change="checkRole" :readonly="(add_menu.role_type=='admin')"/>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row >
                            <Col span="23"style="width:97%" >
                                <FormItem label="角色类型：" prop="role_type">
                                    <template v-if="add_menu.role_type==='admin'">
                                        <Input value="系统管理" :readonly="true" style="width:200px"/>
                                    </template>
                                    <template v-else>
                                        <Select  v-model="add_menu.role_type" style="width:200px">
                                            <Option v-for="item in typeList" :value="item.value" :key="item.value">{{item.label}}</Option>
                                        </Select>
                                    </template>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row >
                            <Col span="23" style="width:97%">
                                <FormItem label="角色描述：" prop="des">
                                    <Input v-model="add_menu.des" type="textarea" :rows="3"/>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Modal>
                <Drawer title="权限管理" v-model="permShow" width="650" :mask-closable="false">
                    <p><strong>菜单访问权限：</strong></p>
                    <Tree :data="newMenuList" :show-checkbox="true" @on-check-change="changeMenuPerm" :check-strictly="true" :check-directly="true"></Tree>
                    <div style="border-bottom:1px solid #dcdae2;" />
                    <p style="padding-top:16px"><strong>API访问权限：</strong></p>
                    <Tree :data="apiList" show-checkbox @on-check-change="addAPI"></Tree>
                    <div class="demo-drawer-footer">
                        <Button style="margin-right: 8px"  @click="cancelPerm">取消</Button>
                        <Button  type="primary" @click="okPerm">确定</Button>
                    </div>
                </Drawer>
            </div>
        </div>
    </div>
</template>

<script>
    import expandRow from './role_expand.vue'
    import usermain from "./user_main"
    import mpage from "../comp_chatter/mpage"
    import pheader from "../comp_chatter/pheader"
    import mheader from "../comp_chatter/mheader"
    import mcontainer from "../comp_chatter/mcontainer"
    import Axios from 'axios'
    import ajax from "../ajax_util"
    import inputSearch from '../base/input_search'

    export default {
        components: {expandRow, usermain, mpage, mheader, mcontainer, pheader, inputSearch},
        data () {
            const validateRole_name = (rule, value, callback) => {
                this.role_repetition=-1;
                if(value === ''){
                    callback(new Error('请输入角色名称.'));
                }
                // else if( (!this.add_menu.isupdate) || (this.add_menu.isupdate&&this.ifRole) ){
                //     //console.log("-----ttttt----",this.role_nameList,value);
                //     for(var i=0; i<this.role_nameList.length; i++){
                //         if(value === this.role_nameList[i]){
                //             //console.log("-----validateRole_name----",this.role_nameList,value);
                //             this.role_repetition=1;
                //             callback(new Error('该角色已存在!'));
                //         }
                //     }
                //     callback();
                // }
                else{
                    callback();
                }
            };
            return {
                tableLoading: false,
                ruleInline: {
                    role_name: [
                        { required: true, validator: validateRole_name, trigger: 'blur' }
                    ],
                    role_type: [
                        { required: true, message: '请选择角色类型.', trigger: 'change' }
                    ],
                    des: [
                        { required: true, message: '请输入角色描述.', trigger: 'blur' }
                    ]
                },
                add_menu:{
                  show:false,
                  role_name:"",
                  role_type:"",
                  des:"",
                  isupdate:false,
                  updateId:-1
                },
                loading: true,
                data: [],
                role_nameList:[],
                role_repetition:-1,

                page:1,
                pageSize:10,
                total:0,
                search_param:'',
                filterList:[],
                countRole:[],
                methodId:'0',

                role_id:-1,
                permShow:false,
                menuList:[],
                permList:[],
                apiList:[],
                treeList:[],
                checkList:[11],
                addPerms:[11],

                newMenuList:[],

                temp_role:"",
                ifRole:false,

                typeList:[
                    {
                        value:"business",
                        label:"运营管理"
                    },
                    {
                        value:"operation",
                        label:"运维管理"
                    },
                    {
                        value:"safe",
                        label:"安全管理"
                    },
                    {
                        value:"entry",
                        label:"普通角色"
                    }
                ]
            }
        },
        computed: {
            columns () {
                let columns = [];
                columns.push({
                    type: 'expand',
                    width: 50,
                    render: (h, params) => {
                        return h(expandRow, {
                            props: {
                                row: params.row
                            }
                        })
                    }
                });
                columns.push({
                    title: '角色名称',
                    key: 'role_name',
                    slot:'role_name',
                    width:'150px'
                });
                columns.push({
                    title: '角色类型',
                    key: 'role_type',
                    slot:'role_type',
                    width:'120px',
                    filters: [
                       {
                            value:"admin",
                            label:"系统管理"
                        },
                        {
                            value:"business",
                            label:"运营管理"
                        },
                        {
                            value:"operation",
                            label:"运维管理"
                        },
                        {
                            value:"safe",
                            label:"安全管理"
                        },
                        {
                            value:"entry",
                            label:"普通角色"
                        }
                    ],
                    filterRemote(value){
                        this.search(this.search_param,value,0);
                    }
                });
                columns.push({
                    title: '角色描述',
                    slot: 'des'
                });
                columns.push({
                    title: '角色下的用户',
                    slot: 'users',
                    width:250
                });
                if (this.$hasPerm('rolePerm') || this.$hasPerm('roleEdit') || this.$hasPerm('roleMove')){
                    columns.push({
                        title: '操作',
                        key: 'action',
                        width: 220,
                        align: 'center',
                        slot: "action",
                    });
                }
                return columns;
            }
        },
        mounted() {
            this.search(this.search_param,this.filterList,0);
        },
        methods: {
            showUsers(users){
                var str = "";
                for(var i=0; i<users.length; i++){
                    str = str + users[i].user_name + "、"
                }

                str = str.slice(0,str.length-1);
                return str;
            },
            // get_all_role(){
            //     this.tableLoading = true
            //     var that=this;
            //     var url=this.CONFIG.url_know+'/getRolesName';
            //     ajax.get({
            //       url:url,
            //       that:that,
            //       success:function(data){
            //         //console.log("=====data=======",data);
            //         that.role_nameList = data;
            //         that.search(that.search_param,that.filterList,0);
            //     }})
            // },
            search(param,value,number){
                this.tableLoading = true;

                if(param === undefined || param === null){
                    param = "";
                }
                if(value === undefined || value === null){
                    value = [];
                }
                if(number == 0){
                    this.page = 1;
                }

                this.search_param = param;
                this.filterList = value;
                var pageModel = {};
                pageModel.page = this.page;
                pageModel.pageSize = this.pageSize;
                pageModel.param = this.search_param;
                pageModel.filter = this.filterList;
                var that=this;
                var url=this.CONFIG.url_know+'/searchRoles';
                ajax.post({
                  url:url,
                  that:that,
                  data:pageModel,
                  success:function(data){
                    //console.log("----data-------",data);
                    that.total = data.total;
                    that.data = data.roleList;
                    that.tableLoading = false;
                }})
            },
            changePage (page) {
                this.page = page;
                this.search(this.search_param,this.filterList,1);
            },
            changePageSize(pageSize){
                this.pageSize = pageSize;
                this.search(this.search_param,this.filterList,0);
            },
            messageWarningFn (text) {
              this.$Message.warning(text)
              setTimeout(() => {
                this.loading = false
                this.$nextTick(() => {
                  this.loading = true
                });
              }, 0.1);
            },
            cancel(name){
                this.$refs[name].resetFields();
                this.ifRole = false;
                this.role_repetition = -1;
            },
            checkRole(){
                if(this.add_menu.role_name == this.temp_role){
                    this.ifRole = false;
                }else{
                    this.ifRole = true;
                }
            },
            add_ok(){
                var that=this;
                if (this.add_menu.role_name === '') {
                    this.messageWarningFn('角色名称不能为空!');
                    return
                }
                // else if(this.role_repetition===1){
                //     //console.log("----55555------",this.role_repetition);
                //     this.messageWarningFn('该角色已存在!');
                //     return
                // }
                else if( this.add_menu.role_type === '' || this.add_menu.role_type === undefined){
                    this.messageWarningFn('角色类型不能为空!');
                    return
                }else if( this.add_menu.des === ''){
                    this.messageWarningFn('角色描述不能为空!');
                    return
                }else{
                    var url=this.CONFIG.url_know+'/role'
                    let role={
                      role_name:this.add_menu.role_name,
                      role_type:this.add_menu.role_type,
                      des:this.add_menu.des,
                      ifRole:this.ifRole
                    };
                    if(this.add_menu.isupdate){//说明是修改，不是新增
                      //console.log("-----role--------",role)
                      role["id"]=this.add_menu.updateId;
                      ajax.put({
                        url:url,
                        that:that,
                        data:role,
                        success:function(data){
                          //that.get_all_role();
                          if(data == "0" && that.ifRole){
                            that.messageWarningFn('该角色名称已存在!');
                          }else if(data == "1"){
                            that.$Notice.success({
                                title: '成功修改角色'
                            });
                            that.add_menu.show=false;
                            that.ifRole = false;
                            that.search(that.search_param,that.filterList,1);
                          }else{
                            that.messageWarningFn(data);
                          }
                        }
                      })
                    }else{//说明是新增
                        //console.log("-----role--------",role)
                        ajax.post({
                            url:url,
                            that:that,
                            data:role,
                            success:function(data){
                                //that.get_all_role();
                                if(data == "0"){
                                    that.messageWarningFn('该角色名称已存在!');
                                } else if(data == "1"){
                                    that.$Notice.success({
                                        title: '成功新建角色'
                                    });
                                    that.add_menu.show=false;
                                    that.ifRole = false;
                                    that.search(that.search_param,that.filterList,0);
                                }else{
                                    that.messageWarningFn(data);
                                }

                            }
                        })
                    }
                }
            },
            add(){
                this.add_menu.isupdate=false;
                this.add_menu.show=true;
                this.add_menu.role_name="";
                this.add_menu.role_type="";
                this.add_menu.des="";
            },
            edit(index,row){
                this.add_menu.isupdate=true;
                this.add_menu.updateId=row.id;
                this.add_menu.show=true;
                this.add_menu.role_name=row.role_name;
                this.add_menu.role_type=row.role_type
                this.add_menu.des=row.des;

                this.temp_role = row.role_name;
            },
            deleteRole(row){
                if(row.role_type === "admin"){
                    this.$Modal.warning({
                            title: '该角色为系统管理员，不能删除!',
                            width:'365'
                    });
                }else{
                    this.$Modal.confirm({
                        title: '确定删除该角色？',
                        width:'360',
                        onOk:() => {
                            this.del(row.id)
                        }
                    });
                }
            },
            del(id) {
                var that=this;
                var url=this.CONFIG.url_know+'/role/'+id;
                ajax.del({
                  url:url,
                  that:that,
                  success:function(data){
                    if(data == "1"){
                        if(that.data.length === 1 && that.page > 1){
                            that.page = that.page-1;
                        }
                        that.search(that.search_param,that.filterList,1);
                        that.$Notice.success({
                          title: '成功删除角色'
                        });
                    }else{
                        that.messageWarningFn(data);
                    }
                  }
                });
            },

            //限制权限窗口
            permMenu(id,role_type){
                if(role_type === 'admin'){
                    this.$Modal.warning({
                        title: '系统管理员拥有所有权限，不能修改!',
                        width:'380'
                    });
                }else{
                    this.permCode(id);
                    this.api(id);

                    this.permShow=true;
                    this.role_id = id;
                    var that = this;
                    var url = this.CONFIG.url_know+'/menu/' + id;
                    ajax.get({
                      url:url,
                      that:that,
                      success:function(data){
                          that.newMenuList = data[0].children
                        //console.log("data------->",data)
                    }});
                }
            },
            //获取角色下可用得菜单
            permCode(id){
                this.checkList = [11];
                var that = this;
                var url = this.CONFIG.url_know+'/perm/' + id;
                ajax.get({
                  url:url,
                  that:that,
                  success:function(data){
                    for(var i=0; i<data.length; i++){
                        if(data[i] != null && that.checkList.indexOf(data[i].id) < 0){
                            that.checkList.push(data[i].id);
                        }
                    }
                    that.perm();
                }});
            },
            perm(){
                var that = this;
                var url = this.CONFIG.url_know+'/perms';
                ajax.get({
                  url:url,
                  that:that,
                  success:function(data){
                    var tempList = [];
                    for(var i=0; i<data.length; i++){
                        if(that.checkList.indexOf(data[i].menu_id) > -1){
                            var temp = {};
                            temp.id = data[i].id;
                            temp.perm_name = data[i].perm_name;
                            temp.menu_id = data[i].menu_id;
                            tempList.push(temp);
                        }else {
                            var index = that.checkList.indexOf(data[i].id);
                            if(index > -1){
                                that.checkList.splice(index,1);
                            }
                        }
                    }
                    that.permList = tempList;
                }})
            },
            api(id){
                var that = this;
                var url = this.CONFIG.url_know+'/api/' + id;
                ajax.get({
                  url:url,
                  that:that,
                  success:function(data){
                    that.apiList = data;
                    that.getAPI(id);
                }});
            },
            getAPI(id){
                var that = this;
                var url = this.CONFIG.url_know+'/perms/' + id;
                ajax.get({
                  url:url,
                  that:that,
                  success:function(data){
                    that.treeList = data;
                    //console.log("-------------------",that.treeList);
                }});
            },
            //修改api权限
            addAPI(tree){
                //console.log("tree-------->",apiList)
                var temp = [];
                for(var i=0; i<tree.length; i++){
                    if(tree[i].hasOwnProperty("key")){
                        temp.push(tree[i].key);
                    }
                }
                this.treeList = temp;
            },
            //修改菜单权限
            changeMenuPerm(tree){
                this.checkList = []
                tree.forEach(item =>{
                    this.checkList.push(item.id)
                })
                //console.log("_----------------------->>>>>",this.checkList)
                var temp = JSON.stringify(this.newMenuList)
                var t = JSON.parse(temp)
                this.setMenu(t)
                this.$nextTick(() => {
                    this.newMenuList = t
                })

            },
            setMenu(tree){
                // console.log("tree---->",tree)
                var isCheck = false
                tree.forEach((item,index) =>{
                    var childrentemp = false
                    //console.log("---->",item.title,isCheck)
                    if(item.checked === undefined){
                        item.checked = false
                    }
                    if(item.children != undefined && item.children.length > 0){
                        childrentemp = this.setMenu(item.children)
                    }else if(item.checked){
                        //console.log("tem.checke--------->",item.title,item.checked)
                        childrentemp = item.checked
                    }
                    if(childrentemp && !item.checked ){
                        //console.log("push------>", item.title,isCheck,item.checked)
                        this.checkList.push(item.id)
                        item.checked = true
                    }
                    if(item.checked){
                        //console.log("11111--------->",item.title,item.checked,isCheck)
                        isCheck = true
                    }
                })
                return isCheck
            },
            //报存权限设置
            okPerm(){
                //console.log("---treeList------------->>",this.treeList);
                //console.log("--this.checkList-------------->>",this.checkList);
                var temp = this.checkList.concat(this.treeList);
                //console.log("temp ----->",temp)
                this.addPerms = temp;
                var that = this;
                var url = this.CONFIG.url_know+'/perms';
                let user_role = {
                    role_id:this.role_id,
                    addPerms:this.addPerms
                };
                ajax.put({
                  url:url,
                  that:that,
                  data:user_role,
                  success:function(data){
                    that.$Notice.success({
                        title: '成功修改角色权限!'
                    });
                    that.permList = [];
                }});
                that.permShow=false;
            },
            cancelPerm(){
                this.permList = [];
                this.apiList = [];
                this.permShow=false;
            }
        }
    }
</script>
